package com.zzyk.main.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.zzyk.main.configuration.exception.UserException;
import com.zzyk.main.mapper.*;
import com.zzyk.main.model.pojo.RdUserArea;
import com.zzyk.main.model.pojo.SysRole;
import com.zzyk.main.model.pojo.SysUser;
import com.zzyk.main.model.pojo.UserRole;
import com.zzyk.main.model.vo.UserInfo;
import com.zzyk.main.model.vo.WxUser;
import com.zzyk.main.service.IMsgService;
import com.zzyk.main.service.ISysUserService;
import com.zzyk.main.utils.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysWxUserDao sysWxUserDao;
    @Autowired
    private IMsgService msgService;
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private GroupDeviceMapper groupDeviceMapper;
    @Resource
    private RdUserAreaMapper rdUserAreaMapper;

    @Override
    public SysUser login(String username) {
        return sysUserDao.getUser4Auth(username);
    }

    @Override
    public UserInfo apiLogin(String username, String password) throws UserException {
        UserInfo user = sysUserDao.getUserByUsernameWithRole(username);
        checkPassword(username, password);
        user.setPassword(null);
        checkUser(user);
        return user;
    }

    @Override
    public UserInfo apiLogin(SysUser sysUser) throws UserException {
        return apiLogin(sysUser.getUsername(), sysUser.getPassword());
    }

    @Override
    public UserInfo apiLogin(String openId) throws UserException {
        WxUser wxUser = sysWxUserDao.getUserByOpenId(openId);
        if (wxUser == null) {
            throw new UserException("用户不存在");
        }
        UserInfo user = sysUserDao.getUserByIdWithRole(wxUser.getUserId());
        checkUser(user);
        return user;
    }

    private void checkUser(SysUser sysUser) throws UserException {
        if (sysUser.getStatus() == 0) {
            throw new DisabledAccountException("用户被禁用");
        }
        Date expire = sysUser.getExpire();
        if (expire != null) {
            DateTime ex = new DateTime(expire);
            if (ex.isBefore(new Date())) {
                throw new DisabledAccountException("账号已过期");
            }
        }
        if (sysUser.getRoleSet() == null) {
            throw new UserException("用户未分配角色");
        }
        boolean flag = false;
        for (SysRole sysRole : sysUser.getRoleSet()) {
            if (sysRole.getType() == 0) {
                flag = true;
            }
        }
        if (!flag) {
            throw new UserException("银行用户禁止登录");
        }
    }

    @Override
    public UserInfo getUser(int userId) {
        return sysUserDao.getUserById(userId);
    }

    @Override
    public UserInfo getUser(String username) {
        return sysUserDao.getUserByUsername(username);
    }

    @Override
    public UserInfo getUserWithRole(int userId) {
        return sysUserDao.getUserByIdWithRole(userId);
    }

    @Override
    public UserInfo getUserWithRole(String username) {
        return sysUserDao.getUserByUsernameWithRole(username);
    }

    @Override
    public SysUser getUserWithRoleAndPermission(String username) {
        return sysUserDao.getUserByUsernameWithRoleAndPermission(username);
    }

    /**
     * 查找用户列表 模糊查询 用户名和用户昵称
     * type=0 查询所有符合条件的用户
     * type=1 查询权限区域符合条件的用户
     * type=2 查询归属企业符合条件的用户
     * type=-1 查询所有内置用户
     *
     * @param userInfo
     * @param type
     * @return
     */
    @Override
    public List<UserInfo> getUserList(UserInfo userInfo, int type) {
        if (type == 0) {
            return sysUserDao.getUserList(userInfo);
        } else if (type == 1) {
            return sysUserDao.getUserListByArea(userInfo);
        } else if (type == 2) {
            return sysUserDao.getUserListByOrganization(userInfo);
        } else if (type == -1) {
            return sysUserDao.getReadonlyUserList();
        } else {
            return null;
        }
    }

    @Override
    public List<UserInfo> getUserByOrganizationId(int organizationId) {
        return sysUserDao.getUserByOrganizationId(organizationId);
    }

    @Override
    public int addUser(SysUser sysUser) throws UserException {
        UserInfo userByUsername = sysUserDao.getUserByUsername(sysUser.getUsername());
        if (ObjectUtil.isNotNull(userByUsername)) {
            throw new UserException("手机号已存在");
        }
        if (StringUtils.isBlank(sysUser.getPassword())) {
            sysUser.setPassword("123456");
        }
        int addUser = sysUserDao.newUser(sysUser);
        if (ObjectUtil.isNotNull(sysUser.getId()) && addUser > 0) {
            for (String area : sysUser.getArea()) {
                RdUserArea userArea = new RdUserArea();
                userArea.setUser(sysUser.getId());
                userArea.setOrganization(Integer.parseInt(area));
                rdUserAreaMapper.insert(userArea);
            }
            UserInfo userById = sysUserDao.getUserById(sysUser.getId());
            if (userById.getStatus() == 1) {
                msgService.activationSend(userById.getUsername(), "SMS_207501642");
            }
        }
        return addUser;
    }

    @Override
    public void checkPassword(String username, String password) throws UserException {
        SysUser user = sysUserDao.getUser4Auth(username);
        if (user == null) {
            throw new UserException("用户名或密码错误");
        }
        if (!user.getPassword().equalsIgnoreCase(MD5Utils.sign(password + user.getCreateTime().getTime() / 1000))) {
            throw new UserException("用户名或密码错误");
        }
    }

    @Override
    public int updateUser(SysUser sysUser) {
        sysUser.setUpdateTime(new Date());
        if (ObjectUtil.isNotNull(sysUser.getId())) {
            UserInfo userById = sysUserDao.getUserById(sysUser.getId());
            if (userById.getStatus() == 0 && sysUser.getStatus() == 1) {
                msgService.activationSend(userById.getUsername(), "SMS_205465134");
            }
        }
        return sysUserDao.updateUser(sysUser);
    }

    @Override
    public int deleteUser(int userId) {
        return sysUserDao.deleteUser(userId);
    }

    @Override
    public List<UserInfo> getUserByOrganizationType(int orgType) {
        return sysUserDao.getUserByOrganizationType(orgType);
    }

    @Override
    public WxUser getWxUserByOpenId(String openId) {
        WxUser userByOpenId = sysWxUserDao.getUserByOpenId(openId);
        return userByOpenId;
    }

    @Override
    public WxUser getWxUserByUserId(Integer userId) {
        return sysWxUserDao.getUserByUserId(userId);
    }

    @Override
    public int addWxUser(WxUser wxUser) {
        return sysWxUserDao.addRecord(wxUser);
    }

    @Override
    public int delWxUser(int id) {
        return sysWxUserDao.delRecord(id);
    }

    @Override
    public int delWxUserByOpenId(String openId) {
        return sysWxUserDao.delWxUserByOpenId(openId);
    }

    @Override
    @Transactional
    public void newUser(SysUser sysUser) throws UserException {
        UserInfo userByUsername = sysUserDao.getUserByUsername(sysUser.getUsername());
        if (ObjectUtil.isNotNull(userByUsername)) {
            throw new UserException("手机号已存在");
        }
        sysUserDao.newUser(sysUser);
        SysRole role = sysRoleDao.getDefaultRole();
        if (ObjectUtil.isNotNull(sysUser.getId())) {
            msgService.activationSend(sysUser.getUsername(), "SMS_207501642");
            UserRole userRole = new UserRole();
            userRole.setUserId(sysUser.getId());
            userRole.setUserId(sysUser.getId());
            if (ObjectUtil.isNotNull(role.getId())) {
                userRole.setRoleId(role.getId());
                sysRoleDao.addUserRole(userRole);
            } else {
                throw new UserException("添加失败，请联系管理员！");
            }
        }
    }

    @Override
    @Transactional
    public Integer processingUserInformation(String[] area) {
        Integer count = 0;
        List<SysUser> userList = sysUserDao.getAll(area);
        for (SysUser userInfo : userList) {
            Date expire = userInfo.getExpire();
            if (expire != null) {
                DateTime ex = new DateTime(expire);
                if (ex.isBefore(new Date())) {
                    count++;
                    SysUser user = new SysUser();
                    user.setId(userInfo.getId());
                    user.setUpdateTime(new Date());
                    userInfo.setStatus(0);
                    sysUserDao.updateUser(userInfo);
                }
            }
        }
        return count;
    }

    @Override
    public List<UserInfo> getUserByAreas(String[] area) {
        return sysUserDao.getUserListByAreas(area);
    }

    @Override
    public SysUser getUserDetails(String userName) {
        SysUser userDetails = sysUserDao.getUserDetails(userName);
        Integer[] deviceList = groupDeviceMapper.selectDeviceByUser(userDetails.getEnterprise(), userDetails.getId());
        userDetails.setDeviceList(deviceList);
        return userDetails;
    }
}
